<template>
    <div
        :class="['text-20 p-24 box-border', { 'min-loading-height': isLoading }]"
        v-loading="isLoading"
        element-loading-text="加载中....."
    >
        <template v-if="!isLoading">
            <!-- 顶部 -->
            <PageHeader title="等级配置" :is-data-loading="isLoading" @refresh="getLevelList">
                <template #custom>
                    <el-button type="primary" round @click="addMemberLevel">新增会员等级</el-button>
                </template>
            </PageHeader>
            <!-- 无数据 -->
            <template v-if="isNoData"><Empty/></template>
            <template v-else>
                <!-- 会员等级列表 -->
                <div class="flex flex-wrap mt-10">
                    <div
                        class="level-box mr-20"
                        v-for="(item, index) in levelConfig"
                        :key="item.id"
                        :style="{ background: `url(${item.levelBackground})` }"
                    >
                        <div class="flex-between-box text-white flex-col w-full">
                            <div class="flex-between-items-box">
                                <span>{{ item.levelName }}</span>
                                <template v-if="item.isDefault">
                                    <span class="default-level">默认等级</span>
                                </template>
                            </div>
                            <div class="flex-between-items-box">
                                <span class="text-14">等级规则：消费金额达到 {{ item.levelRule }} 元</span>
                                <div class="flex">
                                    <Icon
                                        name="Edit"
                                        class="cursor-pointer"
                                        :size="17"
                                        @click="editLevel(item)"
                                    />
                                    <template v-if="index">
                                        <!-- 删除 -->
                                        <Icon
                                            class="cursor-pointer ml-10"
                                            name="Delete"
                                            :size="16"
                                            @click="confirmDelete(item.id)"
                                        />
                                    </template>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </template>
        </template>
        <!-- 等级配置弹窗 -->
        <el-dialog
            v-model="levelDialogVisible"
            width="25%"
            :title="levelDialogTitle"
            :before-close="levelHandleClose"
        >
            <!-- 表单 -->
            <el-form
                ref="addLevelFormRef"
                :model="addLevelForm"
                :rules="addLevelRules"
                label-width="110px"
                status-icon
            >
                <el-form-item class="levelName" label="等级名称：" prop="levelName">
                    <el-input placeholder="请输入" type="text" v-model="addLevelForm.levelName"/>
                </el-form-item>
                <el-form-item class="levelRule" label="升级条件：" prop="levelRule">
                    <div class="flex w-full">
                        <span class="flex-shrink-0 mr-8">累计消费金额达到</span>
                        <el-input placeholder="请输入" v-model="addLevelForm.levelRule"/>
                        <span class="ml-8">元</span>
                    </div>
                </el-form-item>
                <el-form-item label="等级背景：" prop="levelBackground">
                    <el-upload
                        class="avatar-uploader"
                        :action="uploadImgURL"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                    >
                        <template v-if="addLevelForm.levelBackground" >
                            <el-image class="avatar" :src="addLevelForm.levelBackground" fit="contain" />
                        </template>
                        <template v-else>
                            <Icon name="Plus" :size="28" color="#8c939d"/>
                        </template>
                    </el-upload>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="levelHandleClose" round>取消</el-button>
                    <el-button type="primary" @click="submitForm(addLevelFormRef)" round>确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessageBox } from 'element-plus'
import { ElMessages, FormRule, timeout } from '@utils/methods'
import { uploadImgURL } from '@/config'
import { HttpResponse } from '@api/http'
import { AddLevelForm,
    httpAddMemberLevel,
    httpDeleteMemberLevel,
    httpMemberLevelList,
    httpUpdateMemberLevel,
    LevelConfig } from '@api/module/memberLevel'
import Icon from '@components/Icon/index.vue'
import PageHeader from '@components/PageHeader/index.vue'
import Empty from '@components/Empty/index.vue'

/**
 * 列表展示
 * */
// 页面加载
const isLoading = ref(true)

// 无数据
const isNoData = ref(false)

// 等级配置列表
const levelConfig = ref<LevelConfig[]>([])

// 获取等级列表
const getLevelList = () => {
    isLoading.value = true
    httpMemberLevelList().then(res => {
        isNoData.value = !res.data
        if (res.data) levelConfig.value = res.data.list
    }).finally(async () => {
        await timeout(500)
        isLoading.value = false
    })
}

getLevelList()

// 删除等级
const confirmDelete = (id: number) => {
    ElMessageBox({
        title: '确认删除',
        message: '当前会员等级下存在会员时无法删除',
        showCancelButton: true,
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        beforeClose: (action, instance, done) => {
            // 确认删除
            if (action === 'confirm') {
                instance.confirmButtonLoading = true
                instance.confirmButtonText = '删除中...'
                // 调用删除接口
                httpDeleteMemberLevel({ id }).then(({ success, message }) => {
                    if (success) {
                        ElMessages.success('删除成功！')
                        getLevelList()
                    } else {
                        ElMessages.error(message!)
                    }
                    instance.confirmButtonLoading = false
                    done()
                })
            } else {
                done()
            }
        }
    }).catch(() => {
        ElMessages.common('取消删除')
    })
}

/**
 * 弹窗
 * */
// 弹窗状态
const levelDialogVisible = ref(false)

// 打开弹窗
const addMemberLevel = () => {
    isEdit.value = false
    levelDialogVisible.value = true
}

/**
 * 表单
 * */
// 校验信息
const addLevelRules = reactive<FormRules>({
    levelName: [
        FormRule.requireRule('请输入等级名称'),
        FormRule.lengthRule(2, 4, '长度在 2-4 个字符')
    ],
    levelRule: [
        FormRule.requireRule('请输入等级规则'),
        FormRule.lengthRule(1, 6, '请输入 1~999999 间的金额')
    ],
    levelBackground: [
        FormRule.requireRule('请上传等级背景')
    ]
})

// 表单实例
const addLevelFormRef = ref<FormInstance>()

// 表单数据
const addLevelForm = reactive<AddLevelForm>({
    levelName: '',
    levelRule: null,
    levelBackground: ''
})

// 等级背景上传成功
const handleAvatarSuccess = ({ data }: HttpResponse) => {
    if (data) {
        addLevelForm.levelBackground = data
        ElMessages.success('上传成功！')
    } else {
        ElMessages.error('上传失败，请重试！')
    }
}

// 确定验证
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(valid => {
        if (valid) {
            // 如果是编辑，则更新
            if (isEdit.value) {
                httpUpdateMemberLevel({
                    ...addLevelForm,
                    id: editDataId.value
                }).then(({ success }) => {
                    submitFormCallBack(success, '修改成功', '修改失败，请重试！')
                })
            } else {
                // 新增会员等级
                httpAddMemberLevel({
                    ...addLevelForm,
                    levelRule: Number(addLevelForm.levelRule),
                    // 如果是第一次添加，需设置为默认值
                    isDefault: levelConfig.value.length ? 0 : 1
                }).then(({ success }) => {
                    submitFormCallBack(success, '新增成功', '新增失败，请重试！')
                })
            }
        }
    })
}

// 提交表单回调
const submitFormCallBack = (success: boolean, successText: string, errorText: string) => {
    // 操作成功，清空表单，关闭弹窗，重新获取数据
    if (success) {
        addLevelFormRef.value?.resetFields()
        levelDialogVisible.value = false
        ElMessages.success(successText)
        getLevelList()
    } else {
        ElMessages.error(errorText)
    }
}

/**
 * 编辑模式
 * */
// 是否编辑模式
const isEdit = ref(false)

// 弹窗标题
const levelDialogTitle = computed(() => (isEdit.value ? '编辑会员等级' : '新增会员等级'))

// 编辑数据
const editDataId = ref()

// 编辑等级
const editLevel = ({ id, levelName, levelRule, levelBackground }: LevelConfig) => {
    isEdit.value = true
    levelDialogVisible.value = true
    // 编辑的 id
    editDataId.value = id
    // 表单赋值
    addLevelForm.levelName = levelName
    addLevelForm.levelRule = levelRule
    addLevelForm.levelBackground = levelBackground
}

// 弹窗关闭前清空表单
const levelHandleClose = () => {
    addLevelForm.levelName = ''
    addLevelForm.levelRule = null
    addLevelForm.levelBackground = ''
    levelDialogVisible.value = false
}
</script>

<style lang="less" scoped>
.level-box{
    @apply mb-20 p-24 box-border rounded-14 flex;
    width: calc((100% - 60px) / 4);
    height: 235px;
    background-size: 100% 100% !important;

    &:nth-child(4n) {
        margin-right: 0;
    }

    .default-level{
        border: 1px solid white;
        padding: 6px 14px;
        @apply rounded-16 flex justify-between items-center text-12;
    }
}

.el-form{
    margin-top: 20px;

    .levelName{
        .el-input, .el-input__wrapper{
            width: 240px;
        }
    }

    .levelRule{
        .el-input, .el-input__wrapper{
            width: 100px;
        }
        :deep(.el-form-item__error){
            left: 120px;
            padding-top: 7px;
        }
    }

    :deep(.el-form-item__error){
        padding-top: 7px !important;
    }

    .el-form-item{
        margin-bottom: 25px;
    }
}

:deep(.el-dialog__footer){
    display: flex;
    justify-content: center;
}
</style>

<style>
.avatar-uploader .el-upload {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 160px;
    height: 160px;
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-tabs__nav-wrap::after{
    background: transparent;
}

.el-message-box{
    border-radius: 14px;
    padding-bottom: 20px;
}
</style>
